/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package blancanieves.back;

import java.util.concurrent.Semaphore;

/**
 *
 * @author pabloramix
 */
public class Comedor {
    
    private static Comedor comedor;
    private final Sitio[] mesa;
    private final Semaphore semaforo;
    
    private Comedor () {
        
        mesa = new Sitio[4];
        semaforo = new Semaphore(4, true);
    }
    
    public static synchronized Comedor getInstance() {
        
        if (comedor == null) {
            comedor = new Comedor();
        }
        
        return comedor;
    }

    public Sitio sentarse() throws InterruptedException {
        
        Thread currentThread;
        semaforo.acquire();
        Sitio s = null;
        
        currentThread = Thread.currentThread();
        
        synchronized(this) {
        
            for (int i = 0; i < mesa.length; i++) {
                if (mesa[i] == null) {
                    s = new Sitio((Enanito) currentThread);
                    mesa[i] = s;
                    break;
                }
            }

        }
        
        if (s == null) {
            System.out.println(currentThread + " Todos los sitios estan ocupados");
        }
        
        return s;
        
    }
    
    public void levantarse(Sitio s) {
        
        for (int i = 0; i < mesa.length; i++) {
            if (mesa[i] != null && mesa[i].equals(s)) {
                mesa[i] = null;
                break;
            }
        }
        
        semaforo.release();
    }
    
    public boolean hayAlguienParaComer() {
        
        boolean res = false;
        
        if (semaforo.tryAcquire(4)) {
            semaforo.release(4);
            return false;
        }
        
        for (Sitio s: mesa) {
            if (s != null) {
                res |= !s.getservido();
            }
        }
        
        return res;
    }
    
    public Sitio[] getMesa() {
        return mesa;
    }
}
